package com.xjh.basestudy.javabase.thread_final.threadlocal.demo;

import java.util.Map;
import javax.websocket.Session;
import org.hibernate.HibernateException;

/**
 * @Author:XuJianHua
 * @Date:2022/10/27
 * @Description: 用ThreadLocal来存储Session
 *
 * 为什么？
 * 为了全局存储sessionId ,存到ThreadLocal中，可以直接根据ThreadLocal去拿
 */
public class Session_Demo {

//  private static final ThreadLocal threadSession = new ThreadLocal();
//
//  public static Session getSession() throws InfrastructureException {
//    Session s = (Session) threadSession.get();
//    try {
//      if (s == null) {
//        s = getSessionFactory().openSession();
//        threadSession.set(s);
//      }
//    } catch (HibernateException ex) {
//      throw new InfrastructureException(ex);
//    }
//    return s;
//
//  }
/**
 *
 * threadLocal存储用户的信息
 *
 * */
  private static final ThreadLocal<Map<String,String>> threadLocal = new ThreadLocal<>();
  public static void map(Map<String,String> map){
    threadLocal.set(map);
  }
  // 获取用户id
  public static String userId(){
    return get("userId");
  }
  // 根据键值获取对应的信息
  public static String get(String key){
    Map<String,String> map = threadLocal.get();
    return map.get(key);
  }
  // 用完清空ThreadLocal
  public static void clear(){
    threadLocal.remove();
  }


}
